<template>
  <div class="publish-page">
    <div class="container">
      <div class="publish-container card">
        <div class="publish-header">
          <h2>发布图文</h2>
        </div>
        
        <div class="publish-content">
          <el-form :model="articleForm" label-position="top" :rules="rules" ref="articleFormRef">
            <!-- 标题 -->
            <el-form-item label="标题" prop="title">
              <el-input 
                v-model="articleForm.title" 
                placeholder="请输入标题（最多50个字）" 
                maxlength="50" 
                show-word-limit>
              </el-input>
            </el-form-item>
            
            <!-- 分类 -->
            <el-form-item label="分类" prop="categoryId">
              <el-select v-model="articleForm.categoryId" placeholder="请选择分类">
                <el-option 
                  v-for="category in categories" 
                  :key="category.id" 
                  :label="category.name" 
                  :value="category.id">
                </el-option>
              </el-select>
            </el-form-item>
            
            <!-- 封面图片 -->
            <el-form-item label="封面图片" prop="img">
              <el-upload
                class="cover-uploader"
                action="http://localhost:9090/file/upload"
                :show-file-list="false"
                :on-success="handleCoverSuccess"
                :before-upload="beforeCoverUpload">
                <img v-if="articleForm.img" :src="articleForm.img" class="cover-image" />
                <el-icon v-else class="cover-uploader-icon"><Plus /></el-icon>
              </el-upload>
              <div class="cover-tip">建议上传16:9比例图片，文件大小不超过2MB</div>
            </el-form-item>
            
            <!-- 摘要 -->
            <el-form-item label="摘要" prop="summary">
              <el-input 
                v-model="articleForm.summary" 
                type="textarea" 
                :rows="3" 
                placeholder="请输入摘要（最多200个字）" 
                maxlength="200" 
                show-word-limit>
              </el-input>
            </el-form-item>
            
            <!-- 内容 -->
            <el-form-item label="内容" prop="content">
              <div class="editor-container">
                <!-- 这里使用简单的textarea代替富文本编辑器 -->
                <!-- 在实际项目中，可以集成第三方富文本编辑器如TinyMCE、CKEditor或wangEditor等 -->
                <el-input 
                  v-model="articleForm.content" 
                  type="textarea" 
                  :rows="10" 
                  placeholder="请输入正文内容...">
                </el-input>
                
                <!-- 图片上传区域 -->
                <div class="image-upload-section">
                  <p class="upload-title">添加图片</p>
                  <el-upload
                    action="http://localhost:9090/file/upload"
                    list-type="picture-card"
                    :limit="9"
                    multiple
                    :on-success="handleContentImageSuccess"
                    :before-upload="beforeImageUpload">
                    <el-icon><Plus /></el-icon>
                  </el-upload>
                  <div class="upload-tip">支持jpg、png格式，单张图片不超过2MB</div>
                </div>
              </div>
            </el-form-item>
            
            <!-- 标签 -->
            <el-form-item label="标签">
              <el-tag
                v-for="tag in dynamicTags"
                :key="tag"
                class="tag-item"
                closable
                @close="handleTagClose(tag)">
                {{ tag }}
              </el-tag>
              <el-input
                v-if="tagInputVisible"
                ref="tagInputRef"
                v-model="tagInputValue"
                class="tag-input"
                size="small"
                @keyup.enter="handleTagConfirm"
                @blur="handleTagConfirm">
              </el-input>
              <el-button v-else class="add-tag-button" size="small" @click="showTagInput">
                + 添加标签
              </el-button>
              <div class="tag-tip">最多添加5个标签，每个标签不超过10个字</div>
            </el-form-item>
            
            <!-- 操作按钮 -->
            <el-form-item>
              <div class="publish-actions">
                <el-button type="primary" @click="submitArticle">发布文章</el-button>
              </div>
            </el-form-item>
          </el-form>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, nextTick } from 'vue'
import {onMounted} from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import request from '@/utils/request'

const router = useRouter()
const authorId = ref(parseInt(localStorage.getItem('id')))
const articleFormRef = ref(null)
const tagInputRef = ref(null)
const tagInputVisible = ref(false)
const tagInputValue = ref('')
const dynamicTags = ref([])
const uploadedImages = ref([])
const categories = ref([])

onMounted(() => {

  // 获取分类列表
  fetchCategories()
})
// 获取分类列表
const fetchCategories = async () => {
  try {
    const res = await request.get('/categories/list')
    
    if (res.data.code === '200') {
      categories.value = res.data.data || []
    } else {
      console.error('获取分类列表失败:', res.data.msg)

    }
  } catch (error) {
    console.error('获取分类列表出错:', error)
  }
}


// 表单数据
const articleForm = reactive({
  title: '',
  categoryId: '',
  summary: '',
  content: '',
  img: '',  // 封面图片
  cover: '' // 正文图片
})

// 验证规则
const rules = {
  title: [
    { required: true, message: '请输入标题', trigger: 'blur' },
    { min: 5, max: 50, message: '标题长度在5到50个字符之间', trigger: 'blur' }
  ],
  categoryId: [
    { required: true, message: '请选择分类', trigger: 'change' }
  ],
  content: [
    { required: true, message: '请输入内容', trigger: 'blur' },
    { min: 20, message: '内容至少20个字符', trigger: 'blur' }
  ],
  summary: [
    { max: 200, message: '摘要不能超过200个字符', trigger: 'blur' }
  ]
}

// 显示标签输入框
const showTagInput = () => {
  if (dynamicTags.value.length >= 5) {
    ElMessage.warning('最多添加5个标签')
    return
  }
  tagInputVisible.value = true
  nextTick(() => {
    tagInputRef.value.focus()
  })
}

// 删除标签
const handleTagClose = (tag) => {
  dynamicTags.value.splice(dynamicTags.value.indexOf(tag), 1)
}

// 确认添加标签
const handleTagConfirm = () => {
  const value = tagInputValue.value.trim()
  if (value) {
    if (value.length > 10) {
      ElMessage.warning('标签不能超过10个字')
    } else if (dynamicTags.value.includes(value)) {
      ElMessage.warning('标签已存在')
    } else if (dynamicTags.value.length >= 5) {
      ElMessage.warning('最多添加5个标签')
    } else {
      dynamicTags.value.push(value)
    }
  }
  tagInputVisible.value = false
  tagInputValue.value = ''
}

// 封面上传前的校验
const beforeCoverUpload = (file) => {
  const isJPGOrPNG = file.type === 'image/jpeg' || file.type === 'image/png'
  const isLt2M = file.size / 1024 / 1024 < 2
  
  if (!isJPGOrPNG) {
    ElMessage.error('封面图片只能是JPG或PNG格式!')
  }
  if (!isLt2M) {
    ElMessage.error('封面图片大小不能超过2MB!')
  }
  
  return isJPGOrPNG && isLt2M
}

// 封面上传成功的回调
const handleCoverSuccess = (res) => {
  console.log(res);
  if (res !== undefined && res !== null) {
    articleForm.img = res
    ElMessage.success('封面上传成功')
  } else {
    ElMessage.error(res.msg || '封面上传失败')
  }
}

// 内容图片上传前的校验
const beforeImageUpload = (file) => {
  const isJPGOrPNG = file.type === 'image/jpeg' || file.type === 'image/png'
  const isLt2M = file.size / 1024 / 1024 < 2
  
  if (!isJPGOrPNG) {
    ElMessage.error('图片只能是JPG或PNG格式!')
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过2MB!')
  }
  
  return isJPGOrPNG && isLt2M
}

// 内容图片上传成功的回调
const handleContentImageSuccess = (res) => {
  console.log('0',res);
  
  if (res !== undefined && res !== null) {
    const imageUrl = res
    uploadedImages.value.push({
      url: imageUrl,
    })
    articleForm.cover = imageUrl
    
    ElMessage.success('图片上传成功')
  } else {
    ElMessage.error(res.msg || '图片上传失败')
  }
}

// 保存文章（公共方法）
const saveArticle = () => {
  // 构建文章数据
  const articleData = {
    ...articleForm,
    authorId:authorId.value,
    tags: dynamicTags.value.join(','), // 将标签数组转换为逗号分隔的字符串
  }
  
  console.log('保存的文章数据:', articleData)
  request.post('/articles/add', articleData).then(res => {
    if (res.data.code === '200') {
      ElMessage.success('文章发布成功')
      router.push('/')
    } else {
      ElMessage.error(res.data.msg || '发布失败')
    }
  }).catch(err => {
    console.error('发布失败:', err)
    ElMessage.error('发布失败，请重试')
  })
}

// 发布文章
const submitArticle = () => {
  articleFormRef.value.validate((valid) => {
    if (valid) {
      saveArticle(true)
    } else {
      return false
    }
  })
}
</script>

<style scoped>
.publish-page {
  padding: 20px 0 40px;
}

.publish-container {
  padding: 20px 30px 30px;
}

.publish-header {
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #f0f0f0;
}

.publish-header h2 {
  font-size: 22px;
  color: #333;
}

.cover-uploader {
  width: 300px;
  height: 169px; /* 16:9比例 */
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  display: flex;
  justify-content: center;
  align-items: center;
}

.cover-uploader:hover {
  border-color: #409eff;
}

.cover-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 40px;
  height: 40px;
}

.cover-image {
  width: 100%;
  height: 100%;
  display: block;
  object-fit: cover;
}

.cover-tip, .upload-tip, .tag-tip {
  font-size: 12px;
  color: #999;
  margin-top: 5px;
}

.editor-container {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 15px;
  background-color: #fff;
}

.image-upload-section {
  margin-top: 20px;
  border-top: 1px dashed #ebeef5;
  padding-top: 15px;
}

.upload-title {
  font-size: 14px;
  margin-bottom: 10px;
  color: #606266;
}

.tag-item {
  margin-right: 10px;
  margin-bottom: 10px;
}

.tag-input {
  width: 120px;
  margin-right: 10px;
  vertical-align: top;
}

.add-tag-button {
  height: 32px;
}

.publish-actions {
  display: flex;
  justify-content: flex-end;
  gap: 15px;
  margin-top: 10px;
}

@media screen and (max-width: 768px) {
  .publish-container {
    padding: 15px;
  }
  
  .cover-uploader {
    width: 100%;
    height: auto;
    aspect-ratio: 16/9;
  }
}
</style> 